package com.qiwenshare.file.config.security.filter;

import com.qiwenshare.common.exception.NotLoginException;
import org.apache.commons.compress.utils.Lists;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.util.PathMatcher;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

/**
 * 自定义未登录异常过滤器 (第一个过滤器)
 * 用于处理Controller外抛出的异常（如Filter抛出的异常）
 */
@Component
public class NoLoginExceptionFilter extends OncePerRequestFilter {

    private List<String> excludes = Lists.newArrayList();
    private List<String> antPaths = Lists.newArrayList();

    public void setExcludes(List<String> excludes) {
        this.excludes = excludes;
    }

    public void setAntPaths(List<String> antPaths) {
        this.antPaths = antPaths;
    }

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        try {
            filterChain.doFilter(request, response);
        } catch (NotLoginException e) {
            e.printStackTrace();
            // 传递异常信息
            request.setAttribute("filterError", e);
            // 指定处理该请求的处理器
            request.getRequestDispatcher("/error/nologin").forward(request, response);
        }
    }

    @Override
    protected boolean shouldNotFilter(HttpServletRequest request) throws ServletException {
        if(excludes.contains(request.getRequestURI()))
            return true;
        PathMatcher pathMatcher = new AntPathMatcher();
        for (String antPath : antPaths) {
            if (pathMatcher.match(antPath, request.getRequestURI())) {
                return true;
            }
        }
        return false;
    }
}
